import pymysql
from wordcloud import WordCloud
import pygal
# 1. 从数据库把所有用户评论取出
# 2. 所有用户评论拼成一个长字符串
# 3. 长字符串用jieba分词
# 4. 拼成词云使用的结构
# 5. pygal 根据用户color，size 统计比例，查询pygal 饼状图文档。


def get_comments():
    # 连接数据库
    # 读表
    # select content from
    db = pymysql.connect(host='127.0.0.1',
                         port=3306,
                         user='root',
                         password='123456',
                         db='jd',
                         charset='utf8mb4')
    with db.cursor() as cursor:
        sql = 'select color from jd.jd'
        cursor.execute(sql)
        s_c = cursor.fetchall()
        # print(s_c)
        list=[]
        for s in s_c:
            list.append(s[0])

        color = ','.join(list)
        print(color)
        color_index(color)

def color_index(color):
    s = color
    # print(s.count("金色"))
    golden = s.count("金色")
    x = color
    # print(x.count("深空灰色"))
    gray = x.count("深空灰色")
    z = color
    # print(z.count("银色"))
    silver = z.count("银色")
    bing_tu(golden, gray, silver)


def bing_tu(golden,gray,silver):
    pie_chart = pygal.Pie()
    pie_chart.title = '购买ipone手机颜色的占比 2018 (in %)'
    pie_chart.add('金色', golden)
    pie_chart.add('银色', silver)
    pie_chart.add('深空灰色', gray)
    pie_chart.render_to_file('33ipone.svg')

if __name__ == '__main__':
    get_comments()